//入口文件
const bloghandleRouther = require("./router/blog")
const userHandleRouther = require('./router/user')
const querystring = require("querystring")
// const { rejects } = require("assert")
setCookieExpries = () => {
    const d = new Date()
    d.setTime(d.getTime() + (24 * 60 * 60 * 1000))
    return d.toGMTString()
}
const getPostData = (req) => {
    return new Promise((resolve, reject) => {
        if (req.method !== "POST") {
            resolve({});
            return;
        }
        if (req.headers["content-type"] !== "application/json") {
            resolve({});
            return;
        }
        let postData = ''
        req.on("data", (chunk) => {
            postData += chunk;
        })
        req.on("end", () => {
            if (!postData) {
                resolve({});
                return;
            }
            resolve(JSON.parse(postData));
        });
    });
};
const serverHandle = (req, res) => {

    res.setHeader("Content-Type", 'application/json');
    const url = req.url;
    req.query = querystring.parse(url.split('?')[1])
    req.path = url.split('?')[0]

    //处理Cookie
    //'username = zhangsan;password=123'转化为json格式
    let cookieStr = {}
    let cookie = req.headers.cookie || ''
    //cookie.split(';'):['username=zhangsan','password=123']
    //forEach针对数组循环，item是数组里的每一项
    cookie.split(';').forEach(item => {
        //[['username','zhangsan'],['password','123']]
        const arr = item.split('=')
        const key = arr[0]
        const value = arr[1]
        //key这个变量作为属性要用中括号
        cookieStr[key] = value
    });
    req.cookie = cookieStr
    console.log(cookieStr);
    //处理session
    let SESSION_DATA = {};
    let needSetCookie = false;
    let userid = req.cookie.userid;
    if (userid) {//cookie中有
        //判断session中有没有
        if (!SESSION_DATA[userid]) {
            SESSION_DATA[userid] = {}
        }
        req.session = SESSION_DATA[userid]
    } else { //cookie没有
        needSetCookie = true
        userid = `${Date.now()}_${Math.random()}`;
        SESSION_DATA[userid] = {};
    }
    req.session = SESSION_DATA[userid]
    // 处理postData
    getPostData(req, res).then(result => {
        req.body = result;

        // 处理 blog 博客接口
        const resData = bloghandleRouther(req, res);
        if (resData) {
            resData.then((val) => {
                res.end(JSON.stringify(val));
            });
            return;
        }

        // 处理user登录接口
        const userData = userHandleRouther(req, res)
        if (userData) {
            if (needSetCookie) {
                res.setHeader('Set-Cookie', `userId=${userId};path=/;httpOnly;expires=${setCookieExpries()}`)
            }
            userData.then((val) => {
                res.end(JSON.stringify(val));
            });
            return;
        }


        res.writeHead(404, '{content-type:text/html}')
        res.write("404 Not Found");
        res.end();
        //    let postData="";
        //    req.on("data",(chunk)=>{
        //     postData+=chunk;
        //    })
        //    req.on('end',()=>{
        //     req.body=JSON.parse(postData)

    });
};
module.exports = serverHandle;